﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.IO;
using System.Windows;
using System.IO.Packaging;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
using Jbe.TestSuite.Infrastructure.Interface.Documents;
using Jbe.TestSuite.RtfEditor.Properties;

namespace Jbe.TestSuite.RtfEditor.Domain
{
    public class XpsExportDocumentType : DocumentType
    {
        public XpsExportDocumentType()
            : base(Resources.XpsDocuments, "xps")
        {
        }


        public override bool CanSave(Document document) { return document is RichTextDocument; }

        protected override void SaveCore(Document document, string fileName)
        {
            FlowDocument flowDocument = ((RichTextDocument)document).Content;
            
            // TODO: Bug - the following code changes the FlowDocument so it is not editable anymore?

            using (Package package = Package.Open(fileName, FileMode.Create))
            {
                using (XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Maximum))
                {
                    XpsSerializationManager serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
                    DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
                    serializer.SaveAsXaml(paginator);
                }
            }
        }
    }
}
